package com.myslef.teaching_platfrom.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.myslef.teaching_platfrom.common.R;
import com.myslef.teaching_platfrom.domain.studentTak.StudentTask;
import com.myslef.teaching_platfrom.domain.studentTak.StudentTaskR;
import com.myslef.teaching_platfrom.domain.task.Task;
import com.myslef.teaching_platfrom.domain.task.TaskR;
import com.myslef.teaching_platfrom.service.StudentTaskService;
import com.myslef.teaching_platfrom.service.TaskService;
import com.myslef.teaching_platfrom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/studentTask")
@CrossOrigin(origins = "http://localhost:8080")
public class StudentTaskController {

    @Autowired
    StudentTaskService sts;
    @Autowired
    TaskService taskService;
    @Autowired
    UserService userService;
    @Value("${upload.dir}") // 读取配置文件中的上传文件保存目录
    private String uploadDir;
    @GetMapping
    public R getTaskLists(@RequestParam("courseId") String courseId,
                          @RequestParam("studentId") Integer studentId){
        List<TaskR> taskList = sts.getTaskLists(Integer.parseInt(courseId), studentId);
        if(taskList!=null)
            return R.success(taskList);
        else
            return R.error("获取列表失败！");
    }

    @GetMapping("/getST")
    public R getTaskL(@RequestParam("taskId") String taskId,
                      @RequestParam("studentId") Integer studentId){
        LambdaQueryWrapper<StudentTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentTask::getTaskId,taskId).eq(StudentTask::getStudentId,studentId);
        StudentTask one = sts.getOne(queryWrapper);
        if(one!=null)
            return R.success(one);
        else
            return R.error("获取列表失败！");
    }
    @GetMapping("/getSTById")
    public R getSTById(@RequestParam("studentTaskId") Integer id){
        LambdaQueryWrapper<StudentTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentTask::getId,id);
        StudentTask one = sts.getOne(queryWrapper);
        if(one!=null)
            return R.success(one);
        else
            return R.error("获取列表失败！");
    }
    @GetMapping("/getTask")
    public R getTask(@RequestParam("taskId") Integer taskId){
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.select(Task::getTaskName,Task::getContent, Task::getDeadline, Task::getTaskUrlList).eq(Task::getId, taskId);
        Task task = taskService.getOne(queryWrapper);
//        User user = userService.getById(Integer.parseInt(studentId));
//
//        if(user == null){
//
//        }

        if(task!=null)
            return R.success(task);
        else
            return R.error("获取列表失败！");
    }

    @PostMapping("/upload")
    public R submitTask(@RequestParam("taskId") Integer taskId,@RequestParam("userId") Integer userId,
                        @RequestParam(required = false,value = "file") MultipartFile[] files,
                        @RequestParam(required = false,value = "content") String content) throws IOException {

        LambdaQueryWrapper<StudentTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentTask::getTaskId,taskId).eq(StudentTask::getStudentId, userId);
        StudentTask one = sts.getOne(queryWrapper);

        Path uploadPath = Paths.get(uploadDir+"/comment/"+System.currentTimeMillis()+userId);
        List<String> list = new ArrayList<>();
        if(files != null)
            for (int i = 0; i < files.length; i++) {
                String originalFileName = files[i].getOriginalFilename();
                if (!Files.exists(uploadPath)) {
                    try {
                        Files.createDirectories(uploadPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Path filePath = Paths.get(uploadPath.toString(), originalFileName);
                list.add(filePath.toString());
                Files.write(filePath, files[i].getBytes());
            }
        String str = String.join(",", list);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(content);
        if(content==null||content.equals("undefined"))
            content = "";
        boolean flag = false;
        System.out.println(content);

        if(one != null) {
            LambdaUpdateWrapper<StudentTask> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StudentTask::getId, one.getId()).set(StudentTask::getContent,content)
                    .set(StudentTask::getTaskUrlList,str).set(StudentTask::getStatus,1).set(StudentTask::getUpdateTime,timestamp);
            flag = sts.update(updateWrapper);
        }
        else{
            StudentTask st = new StudentTask();

            st.setContent(content);
            st.setStudentId(userId);
            st.setTaskId(taskId);
            st.setScore(0);
            st.setStatus(1);//置为已提交状态
            st.setTaskUrlList(str);
            st.setUpdateTime(timestamp);
            flag = sts.save(st);
        }
        if(flag)
            return R.success("提交成功");
        else
            return R.error("提交失败");
    }

    @GetMapping("/getStudentTaskList")
    public R getStudentTaskList(@RequestParam("taskId") String taskId,
                                @RequestParam("courseId") String courseId){
        List<StudentTaskR> studentTask = sts.getStudentTaskList(Integer.parseInt(taskId), Integer.parseInt(courseId));
        if(studentTask!=null)
            return R.success(studentTask);
        else
            return R.error("获取列表失败！");
    }

    @PostMapping("/setScore")
    public R setScore(@RequestBody StudentTask studentTask){
        LambdaQueryWrapper<StudentTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentTask::getId,studentTask.getId());
        StudentTask one = sts.getOne(queryWrapper);
        if(one == null||one.getStatus() == 0){
            return R.error("该同学还未提交作业！");
        }
        LambdaUpdateWrapper<StudentTask> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(StudentTask::getId,studentTask.getId()).set(StudentTask::getScore, studentTask.getScore())
                .set(StudentTask::getStatus, 2);
        boolean update = sts.update(updateWrapper);
        if(update)
            return R.success("修改成功！");
        else
            return R.error("修改失败!");
    }
    @PutMapping("/setStatus/{studentTaskId}")
    public R setStatus(@PathVariable("studentTaskId") String studentTaskId){
        LambdaQueryWrapper<StudentTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentTask::getId, Integer.parseInt(studentTaskId));
        StudentTask one = sts.getOne(queryWrapper);
        if(one == null){
            return R.error("该同学还未提交作业！");
        }
        LambdaUpdateWrapper<StudentTask> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(StudentTask::getId,Integer.parseInt(studentTaskId))
                .set(StudentTask::getStatus, 0);
        boolean update = sts.update(updateWrapper);
        if(update)
            return R.success("修改成功！");
        else
            return R.error("修改失败!");
    }

}
